package com.david.elasticjob.config;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.david.elasticjob.job.PersonJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 * @author David
 * @version V1.0
 * @Package com.david.elasticjob.config
 * @date 2021/5/4 11:01
 */
@Configuration
public class PersonJobConfig {
    @Value("${job.personJob.cron}")
    private  String corn;

    @Value("${job.personJob.shardingTotalCount}")
    private Integer shardingTotalCount;

    @Value("${job.personJob.shardingParameter}")
    private  String shardingParameter;

    @Value("${job.personJob.jobName}")
    private  String jobName;

    @Value("${job.personJob.className}")
    private  String className;
    @Autowired
    private DataSource dataSource;

    @Bean(initMethod = "init")
    public JobScheduler helloJobScheduler(PersonJob personJob, ZookeeperRegistryCenter zookeeperRegistryCenter){

        JobEventConfiguration jobEventConfiguration = new JobEventRdbConfiguration(dataSource);

        return new SpringJobScheduler(personJob,zookeeperRegistryCenter,
                getLiteJobConfiguration(className,jobName,corn,shardingTotalCount),jobEventConfiguration);
    }

    private LiteJobConfiguration getLiteJobConfiguration(String jobClassName,String jobName,String cron,Integer shardingTotalCount){
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount)
                .shardingItemParameters(shardingParameter) //分片参数，前面是分片序号，后面是分片数据 此处0代表女 1代表男
                .build();

        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, jobClassName);
        LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration.newBuilder(simpleJobConfiguration).overwrite(true).build();
        return liteJobConfiguration;

    }
}
